﻿<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <title>投稿管理</title>
    <link rel="stylesheet" href="~/lib/element-ui/theme-chalk/index.css">
    <link rel="stylesheet" href="~/css/default/style.css">
    <!--quill editer-->
    <link rel="stylesheet" href="~/lib/quill/quill.core.css" />
    <link rel="stylesheet" href="~/lib/quill/quill.snow.css" />
    <link rel="stylesheet" href="~/lib/quill/quill.bubble.css" />
    <link rel="stylesheet" href="~/lib/quill/quill-zh-cn.css" />
</head>

<body class="mainbody">
    <div id="app" v-cloak>
        <div class="location">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item>
                    <i class="el-icon-s-home"></i>
                    管理中心
                </el-breadcrumb-item>
                <el-breadcrumb-item>首页</el-breadcrumb-item>
                <el-breadcrumb-item>投稿管理</el-breadcrumb-item>
                <el-breadcrumb-item>编辑投稿</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <div class="content-box">
            <el-form ref="editForm" :model="model" :rules="rules" :label-position="labelPosition" label-width="120px">
                <el-tabs v-model="activeName" type="card">
                    <el-tab-pane label="基本信息" name="info">
                        <div class="tab-content">
                            @*<el-form-item prop="siteId" label="所属站点">
            <el-select v-model="model.siteId" :disabled="model.id>0" placeholder="请选择..." @@change="handleSiteChange">
                <el-option v-for="site in siteList"
                           :key="site.id"
                           :label="site.title"
                           :value="site.id">
                </el-option>
            </el-select>
        </el-form-item>*@
                            <el-form-item prop="channelId" label="所属频道">
                                <el-select v-model="model.channelId" :disabled="model.id>0" placeholder="请选择..." @@change="handleChannelChange">
                                    <el-option v-for="channel in channelList"
                                               :key="channel.id"
                                               :label="channel.title"
                                               :value="channel.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="title" label="标题">
                                <el-input v-model="model.title" placeholder="必填，512字符内"></el-input>
                            </el-form-item>
                            <el-form-item prop="source" label="来源">
                                <el-input v-model="model.source" placeholder="必填，128字符内"></el-input>
                            </el-form-item>
                            <el-form-item prop="author" label="作者">
                                <el-input v-model="model.author" placeholder="必填，128字符内"></el-input>
                            </el-form-item>
                            <el-form-item prop="imgUrl" label="封面图片">
                                <dt-upload-text v-model="model.imgUrl"
                                                placeholder="请上传封面图片"
                                                width="20%"
                                                height="10%"
                                                fit="contain"
                                                :size="sysconfig.imgSize"
                                                exts="jpg,jpeg,png,gif"
                                                action="/upload">
                                </dt-upload-text>
                            </el-form-item>
                            <el-form-item v-show="channelModel.isAlbum==1" label="相册">
                                <dt-upload-album v-model="form.albumList"></dt-upload-album>
                            </el-form-item>
                            <el-form-item v-show="channelModel.isAttach==1" label="附件上传">
                                <dt-upload-attach v-model="form.attachList" :size="sysconfig.attachSize" :exts="sysconfig.fileExtension"></dt-upload-attach>
                            </el-form-item>
                            <el-form-item prop="content" label="内容介绍">
                                <dt-editor v-model="model.content" placeholder="请输入内容介绍"></dt-editor>
                            </el-form-item>
                            <el-form-item label="状态">
                                <el-radio-group v-model="model.status" @@change="handleChangeStatus">
                                    <el-radio-button label="0">待审</el-radio-button>
                                    <el-radio-button label="1">通过</el-radio-button>
                                    <el-radio-button label="2">返回</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="创建时间" v-if="model.id>0">
                                {{model.userName}} {{model.addTime}}
                            </el-form-item>
                            <el-form-item label="最后更新" v-if="model.id>0&&model.updateTime">
                                {{model.updateBy}} {{model.updateTime}}
                            </el-form-item>
                            <el-form-item v-if="status!=1&&model.status==1&&model.id>0" prop="categorys" label="所属父类别">
                                <el-dropdown split-button class="dropdown-tree">
                                    <input type="text" v-model="model.categorys" style="display:none;" />
                                    <div class="dropdown-multiple-tree-lable">{{dropdownMultipleTree.dropdownLable}}</div>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-tree :data="treeCategoryList"
                                                 ref="categoryTree"
                                                 :default-expand-all="true"
                                                 :expand-on-click-node="false"
                                                 @@check="handleDropdownMultipleTreeCheck"
                                                 node-key="id"
                                                 show-checkbox
                                                 :props="defaultProps">
                                        </el-tree>

                                    </el-dropdown-menu>
                                </el-dropdown>
                            </el-form-item>
                        </div>
                    </el-tab-pane>
                    <template v-if="model.fields.length>0">
                        <el-tab-pane label="扩展内容" name="fields">
                            <div class="tab-content">
                                <template v-for="(field,index) in model.fields">
                                    <!--单行文本框-->
                                    <el-form-item v-if="field.controlType=='input'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <el-input v-if="field.isPassword==0" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
                                        <el-input v-else v-model="field.fieldValue" :placeholder="field.validTipMsg" show-password></el-input>
                                    </el-form-item>
                                    <!--多行文本框-->
                                    <el-form-item v-else-if="field.controlType=='textarea'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <el-input type="textarea" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
                                    </el-form-item>
                                    <!--编辑器-->
                                    <el-form-item v-else-if="field.controlType=='editor'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <div style="min-height:230px;">
                                            <dt-editor v-if="field.editorType==0" v-model="field.fieldValue" placeholder="field.validTipMsg"></dt-editor>
                                            <dt-editor mini v-if="field.editorType==1" v-model="field.fieldValue" placeholder="field.validTipMsg"></dt-editor>
                                        </div>
                                    </el-form-item>
                                    <!--图片上传-->
                                    <el-form-item v-else-if="field.controlType=='images'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <dt-upload-text v-model="field.fieldValue"
                                                        :placeholder="field.validTipMsg"
                                                        exts="jpg,jpeg,png,gif"
                                                        :size="sysconfig.imgSize"
                                                        action="/upload">
                                        </dt-upload-text>
                                    </el-form-item>
                                    <!--视频上传-->
                                    <el-form-item v-else-if="field.controlType=='video'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <dt-upload-text v-model="field.fieldValue"
                                                        :placeholder="field.validTipMsg"
                                                        :exts="sysconfig.videoExtension"
                                                        :size="sysconfig.videoSize"
                                                        action="/upload"></dt-upload-text>
                                    </el-form-item>
                                    <!--日期时间-->
                                    <el-form-item v-else-if="field.controlType=='datetime'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <el-date-picker v-model="field.fieldValue" value-format="yyyy-MM-dd hh:mm:ss" :placeholder="field.validTipMsg" type="datetime">
                                        </el-date-picker>
                                    </el-form-item>
                                    <!--多项单选-->
                                    <el-form-item v-else-if="field.controlType=='radio'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <el-radio-group v-model="field.fieldValue">
                                            <el-radio v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <!--多项多选-->
                                    <el-form-item v-else-if="field.controlType=='checkbox'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                        <el-checkbox-group v-model="field.fieldValue">
                                            <el-checkbox v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-checkbox>
                                        </el-checkbox-group>
                                    </el-form-item>
                                </template>
                            </div>
                        </el-tab-pane>
                    </template>
                </el-tabs>
            </el-form>
        </div>

        <div class="footer-box">
            <div class="footer-btn">
                <el-button :disabled="status==1" type="primary" @@click="submitForm">确认保存</el-button>
                <el-button plain @@click="resetForm">返回上一页</el-button>
            </div>
        </div>
    </div>

    <script src="~/lib/vue/vue.js"></script>
    <script src="~/lib/element-ui/index.js"></script>
    <script src="~/lib/axios/axios.min.js"></script>
    <script src="~/lib/babel-polyfill/polyfill.min.js"></script>
    <script src="~/js/axios.config.js"></script>
    <script src="~/js/upload.component.js"></script>
    <!--quill editer-->
    <script src="~/lib/quill/quill.min.js"></script>
    <script src="~/lib/quill/vue-quill-editor.js"></script>
    <script src="~/lib/quill/image-resize.min.js"></script>
    <script src="~/js/editor.component.js"></script>
    <script>
        //初始化VUE
        var ve = new Vue({
            el: '#app',
            data: {
                activeName: 'info',//当前选项卡
                labelPosition: 'right',//表单对齐方式
                form: {
                    albumList: [],//相册列表,保存取值
                    attachList: [],
                },
                model: {
                    id: 0,
                    channelId: '',
                    title: '',
                    source: '',
                    author: '',
                    imgUrl: '',
                    fieldMeta: '',
                    albumMeta: '',
                    attachMeta: '',
                    content: '',
                    userId: 0,
                    userName: '',
                    addTime: '',
                    updateBy: '',
                    updateTime: '',
                    status: 0,
                    fields: [],
                    categorys: [],
                    albums: [],
                    attachs: [],
                },
                //siteList: [],//站点列表
                channelList: [],//频道列表
                channelModel: {},
                sysconfig: {},
                rules: {
                    title: [
                        { required: true, message: '标题不可为空', trigger: 'blur' },
                        { max: 512, message: '标题不可超出512字符', trigger: 'blur' }
                    ],
                    source: [
                        { max: 128, message: '来源不可超出128字符', trigger: 'blur' }
                    ],
                    author: [
                        { max: 128, message: '作者不可超出128字符', trigger: 'blur' }
                    ],
                    imgUrl: [
                        { max: 512, message: '图片地址不可超出512字符', trigger: 'blur' }
                    ],
                    categorys: [
                        { type: 'array', required: true, message: '请选择栏目类别', trigger: 'blur' },
                    ],
                },
                fieldRules: {},
                status: 0,
                treeCategoryList: [],
                dropdownMultipleTree: {
                    dropdownLable: '请选择栏目类别',
                },
                defaultProps: {
                    value: 'id',
                    label: 'title',
                    children: 'children',
                    multiple: true,
                    checkStrictly: true,
                },
            },
            methods: {
                //初始化数据
                initData: function () {
                    let _this = this; //当前页面
                    let id = GetQueryValue("id"); //获取ID
                    let channelId = 0;
                    channelId = GetQueryValue("channelId"); //获取channelId
                    const loading = _this.$loading({ body: true, lock: true });
                    //获取系统信息
                    new Promise(resolve => {
                        AxiosAjax({
                            url: `/setting/sysconfig`,
                            loading: false,
                            success: function (res) {
                                _this.sysconfig = res.data;
                                resolve('ok');
                            }
                        });
                    }).then(val => {
                        return new Promise(resolve => {
                            //频道信息
                            AxiosAjax({
                                url: `/channel/${channelId}`,
                                loading: false,
                                success: function (res) {
                                    _this.channelModel = res.data;
                                    resolve('ok');
                                }
                            });
                        });
                    }).then(val => {
                        return new Promise(resolve => {
                            //获取频道列表
                            AxiosAjax({
                                url: `/channel/view/0?siteId=${_this.channelModel.siteId}`,
                                loading: false,
                                success: function (res) {
                                    _this.channelList = res.data;
                                    _this.model.channelId = parseInt(channelId);
                                    resolve('ok');
                                }
                            });
                        })
                    }).then(val => {
                        return new Promise(resolve => {
                            //获取分类列表
                            AxiosAjax({
                                url: `/article/category/${_this.model.channelId}`,
                                loading: false,
                                success: function (res) {
                                    _this.treeCategoryList = res.data;
                                    resolve('ok');
                                }
                            });
                        })
                    }).then(val => {
                        return new Promise(resolve => {
                            if (id) {
                                AxiosAjax({
                                    url: `/article/contribute/${channelId}/${id}/view`,
                                    loading: false,
                                    success: function (res) {
                                        //赋值给model
                                        Object.keys(_this.model).forEach(key => {
                                            _this.model[key] = res.data[key];
                                        });
                                        //赋值扩展字段
                                        _this.status = _this.model.status;
                                        //相册赋值
                                        if (_this.model.albums) {
                                            _this.model.albums.map(function (item) {
                                                item.url = item.thumbPath;
                                                item.id = 0;
                                                _this.form.albumList.push(item);
                                            })
                                        }
                                        //附件赋值
                                        if (_this.model.attachs) {
                                            _this.model.attachs.map(function (item) {
                                                item.fileName = item.fileName;
                                                item.articleId = item.articleId;
                                                item.filePath = item.filePath;
                                                item.fileSize = item.fileSize;
                                                item.fileExt = item.fileExt;
                                                item.downCount = item.downCount;
                                                item.id = 0;
                                                _this.form.attachList.push(item);
                                            })
                                        }
                                        resolve('ok');
                                    }
                                });
                            } else {
                                //赋值扩展字段
                                _this.model.fields = _this.channelModel.fields;
                                resolve('ok');
                            }
                        });

                    }).then(val => {
                        //获得频道扩展字段
                        _this.initFields();
                        loading.close();
                    });
                },
                submitForm: function () {
                    let _this = this; //当前页面
                    //多个表单验证
                    const f1 = new Promise((resolve, reject) => {
                        _this.$refs['editForm'].validate((valid) => {
                            if (valid) resolve()
                        });
                    });
                    Promise.all([f1]).then(() => {
                        console.log(_this.model);
                        let model = JSON.parse(JSON.stringify(_this.model));
                        console.log(model);
                        debugger;
                        //处理扩展字段
                        model.fields.forEach(function (val, index) {
                            if (Array.isArray(val.fieldValue)) {
                                val.fieldValue = val.fieldValue.join(',');
                            }
                        });
                        //格式化相册数据去除没有上传成功的数据
                        _this.formatAlbum();
                        //格式化附件数据去除没有上传成功的数据
                        _this.formatAttach();
                        //相册取值
                        let albumList = [];
                        _this.form.albumList.map(function (item) {
                            albumList.push({
                                id: 0,
                                articleId: 0,
                                thumbPath: item.thumbPath,
                                originalPath: item.originalPath,
                                remark: item.remark
                            });
                        });
                        model.albums = albumList;
                        //附件取值
                        let attachList = [];
                        _this.form.attachList.map(function (item) {

                            attachList.push({
                                id: 0,
                                fileName: item.fileName,
                                articleId: 0,
                                filePath: item.filePath,
                                fileSize: item.fileSize,
                                fileExt: item.fileExt,
                                downCount: item.downCount,
                            });
                        });
                        model.attachs = attachList;
                        //提交表单,Id大于0则修改，否则添加
                        if (_this.model.id > 0) {
                            AxiosAjax({
                                method: 'put',
                                url: `/article/contribute/${_this.model.channelId}/${_this.model.id}`,
                                data: model,
                                loading: true,
                                successMsg: '修改成功',
                                success: function (res) {
                                    //可跳转加列表页
                                    _this.linkUrl('/article/contributelist');
                                }
                            });
                        } else {
                            AxiosAjax({
                                method: 'post',
                                url: `/article/contribute/${_this.model.channelId}`,
                                data: model,
                                loading: true,
                                successMsg: '新增成功',
                                success: function (res) {
                                    //重置表单
                                    _this.$refs['editForm'].resetFields();
                                    _this.form.albumList = [];
                                    _this.form.attachList = [];
                                    _this.model.albums = [];
                                    _this.model.attachs = [];
                                    _this.model.albumMeta = '';
                                    _this.model.attachMeta = '';
                                    _this.model.fieldMeta = '';
                                    /*_this.model.fields = [];*/
                                    //_this.linkUrl(`/article/contributelist`);
                                }
                            });
                        }
                    })
                },
                //跳转链接
                linkUrl: function (url) {
                    var _this = this;
                    if (url.indexOf('?') >= 0) {
                        url = url + '&channelId=' + _this.model.channelId;
                    } else {
                        url = url + '?channelId=' + _this.model.channelId;
                    }
                    console.log(url);
                    window.location.href = url;
                },
                //返回上一页
                resetForm() {
                    window.history.back(-1);
                },
                //站点发生改变
                //handleSiteChange(val) {
                //    let _this = this;
                //    _this.getChannelList();
                //    _this.model.channelId;
                //},
                //频道变化
                handleChannelChange(val) {
                    let _this = this;
                    _this.getChannelModel(val);
                },
                //获得频道信息
                getChannelModel(channelId) {
                    let _this = this;
                    AxiosAjax({
                        url: `/channel/${channelId}`,
                        loading: false,
                        success: function (res) {
                            _this.channelModel = res.data;
                            _this.model.fields = _this.channelModel.fields;
                            //获得频道扩展字段
                            _this.initFields();

                        }
                    });
                },
                //初始化扩展字段
                initFields() {
                    let _this = this;
                    //重置验证规则
                    _this.fieldRules = {};
                    //重置表单
                    _this.channelModel.fields.forEach(function (val, i) {
                        //编辑的时候触发
                        if (_this.model.id>0) {
                            //获得扩展字段值
                            let obj = getFieldsValue(val.name);
                            //构建Fields属性
                            val.fieldName = val.name;
                            val.fieldId = obj.id;
                            //如果值存在，将值替换默认值
                            if (obj.value) {
                                //如果是数组
                                if (Array.isArray(val.fieldValue)) {
                                    val.fieldValue = obj.value.split(',');
                                } else {
                                    val.fieldValue = obj.value;
                                }

                            } else {
                                if (Array.isArray(val.fieldValue)) {
                                    val.fieldValue = [];
                                } else {
                                    val.fieldValue = '';
                                }

                            }
                        } else {
                            //构建Fields属性
                            val.fieldName = val.name;
                            val.fieldId = val.id;
                        }
                        //生成验证规则
                        getRules(val);
                    });
                    _this.model.fields = _this.channelModel.fields;
                    //获得扩展字段值
                    //function getFieldsValue(name) {
                    //    let obj = { value: '', id: 0 };
                    //    if (_this.model.fields.length > 0) {
                    //        _this.model.fields.forEach(function (val, index) {
                    //            if (val.fieldName == name) {
                    //                obj = { value: val.fieldValue, id: val.fieldId };
                    //            }
                    //        });
                    //    }
                    //    return obj;
                    //}
                    function getFieldsValue(name) {
                        let obj = { value: '', id: 0 };
                        let fields = JSON.parse(_this.model.fieldMeta)
                        if (fields.length > 0) {
                            fields.forEach(function (val, index) {
                                if (val.fieldName == name) {
                                    obj = { value: val.fieldValue, id: val.fieldId };
                                }
                            });
                        }
                        return obj;
                    }
                    //生成验证规则
                    function getRules(obj) {
                        let item = [];
                        //blur验证的控件
                        if (obj.controlType == 'input' ||
                            obj.controlType == 'textarea' ||
                            obj.controlType == 'editor' ||
                            obj.controlType == 'images' ||
                            obj.controlType == 'video' ||
                            obj.controlType == 'datetime'
                        ) {
                            //必填项
                            if (obj.isRequired == 1) {
                                let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'blur' };
                                item.push(eleRule);
                            }
                            //检查正则是否为null
                            if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
                                //不为空，将字符串转成正则表达式
                                let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'blur' }
                                item.push(eleRule);
                            }

                        } else if (obj.controlType == 'radio' ||
                            obj.controlType == 'checkbox') {
                            //change验证的控件
                            //必填项
                            if (obj.isRequired == 1) {
                                let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'change' };
                                item.push(eleRule);
                            }
                            //检查正则是否为null
                            if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
                                //不为空，将字符串转成正则表达式
                                let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'change' }
                                item.push(eleRule);
                            }
                        }
                        let name = obj.name;
                        _this.fieldRules[name] = item;
                    };
                },
                //下拉树
                handleDropdownMultipleTreeCheck() {
                    let _this = this;
                    //获取所有选中的节点只有全选节点
                    let selectedNodes = _this.$refs.categoryTree.getCheckedNodes();
                    let lableArr = new Array();//显示选中的值
                    let categorys = [];
                    selectedNodes.forEach(ele => {
                        lableArr.push("【" + ele.title + "】");
                        categorys.push(ele.id);
                    });
                    if (lableArr.length > 0) {
                        _this.model.categorys = categorys;
                        _this.dropdownMultipleTree.dropdownLable = lableArr.join(',');
                    } else {
                        _this.model.categorys = [];
                        _this.dropdownMultipleTree.dropdownLable = '请选择栏目类别';
                    }
                },
                //点击状态按钮
                handleChangeStatus(val) {
                    let _this = this;
                    _this.model.categorys = [];
                    _this.dropdownMultipleTree.dropdownLable = '请选择栏目类别';
                },
                //格式化相册数据
                formatAlbum() {
                    let _this = this;
                    let albumsArr = [];
                    if (_this.model.albums) {
                        let albums = _this.model.albums;
                        for (let i = 0; i < albums.length; i++) {
                            if (albums[i].status === 'success') {
                                albumsArr.push(albums[i]);
                            }
                        }
                        _this.model.albums = albumsArr;
                    }
                },
                //格式化附件数据
                formatAttach() {
                    let _this = this;
                    let attachArr = [];
                    if (_this.model.attachs) {
                        let attachs = _this.model.attachs;
                        for (let i = 0; i < attachs.length; i++) {
                            if (attachs[i].status === 'success') {
                                attachArr.push(attachs[i]);
                            }
                        }
                        _this.model.attachs = attachArr;
                    }
                },
            },
            mounted: function () {
                //初始化数据
                this.initData();
            }
        })
    </script>
</body>
</html>
